<?php

namespace App\Http\Controllers\Admin;

use App\Models\Address;
use App\Models\AuthGroupAccess;
use App\Models\BackLogData;
use App\Models\Brand;
use App\Models\BucketCategory;
use App\Models\BucketData;
use App\Models\BucketLog;
use App\Models\Goods;
use App\Models\GoodsCategory;
use App\Models\Member;
use App\Models\MemberCash;
use App\Models\MemberCommission;
use App\Models\MemberWaterBillLog;
use App\Models\MemberWithdraw;
use App\Models\Notice;
use App\Models\Order;
use App\Models\Picture;
use App\Models\Printer;
use App\Models\PrivateCode;
use App\Models\ReferCode;
use App\Models\ScoreGoods;
use App\Models\Service;
use App\Models\Shop;
use App\Models\ShopAccount;
use App\Models\ShopBucketCategory;
use App\Models\ServiceCharge;
use App\Models\ShopGoods;
use App\Models\ShopGoodsStock;
use App\Models\ShopWaterBillCategory;
use App\Models\Statistic;
use App\Models\WaterBill;
use App\Models\WaterBillCategory;
use App\Models\WaterBillOrder;
use App\Models\WechatSet;
use App\Models\Worker;
use App\Models\WxPay;
use App\Models\WxTpl;
use App\Support\WechatSilentAuth;
use QrCode;

class SingleController extends BaseController
{

    public function __construct(
        Member $member,
        MemberCash $memberCash,
        Shop $shop,
        BucketData $bucketData,
        ShopBucketCategory $shopBucketCategory,
        WaterBill $waterBill,
        Order $order,
        Picture $picture,
        ShopGoods $shopGoods,
        GoodsCategory $goodsCategory,
        Brand $brand,
        BucketCategory $bucketCategory,
        Goods $goods,
        BucketLog $bucketLog,
        WaterBillCategory $waterBillCategory,
        ShopWaterBillCategory $shopWaterBillCategory,
        Worker $worker,
        WechatSet $wechatSet,
        Notice $notice,
        BackLogData $backLogData,
        ServiceCharge $serviceCharge,
        AuthGroupAccess $authGroupAccess,
        Service $service,
        WxPay $wxPay,
        WxTpl $wxTpl,
        WaterBillOrder $waterBillOrder,
        Printer $printer,
        ShopAccount $shopAccount,
        Statistic $statistic,
        PrivateCode $privateCode,
        ReferCode $referCode,
        MemberCommission $commission,
        MemberWithdraw $memberWithdraw,
        ScoreGoods $scoreGoods,
        Address $address,
        ShopGoodsStock $goodsStock,
        WechatSilentAuth $silentAuth,
        MemberWaterBillLog $memberWaterBillLog
    )
    {
        parent::__construct();
        $this->member = $member;
        $this->memberCash = $memberCash;
        $this->shop = $shop;
        $this->bucketData = $bucketData;
        $this->waterBill = $waterBill;
        $this->shopBucketCategory = $shopBucketCategory;
        $this->order = $order;
        $this->picture = $picture;
        $this->shopGoods = $shopGoods;
        $this->goodsCategory = $goodsCategory;
        $this->brand = $brand;
        $this->bucketCategory = $bucketCategory;
        $this->goods = $goods;
        $this->bucketLog = $bucketLog;
        $this->waterbillCategory = $waterBillCategory;
        $this->shopWaterBillCategory = $shopWaterBillCategory;
        $this->worker = $worker;
        $this->wechatSet = $wechatSet;
        $this->notice = $notice;
        $this->backLogData = $backLogData;
        $this->serviceCharge = $serviceCharge;
        $this->authGroupAccess = $authGroupAccess;
        $this->service = $service;
        $this->wxPay = $wxPay;
        $this->wxTpl = $wxTpl;
        $this->waterBillOrder = $waterBillOrder;
        $this->printer = $printer;
        $this->shopAccount = $shopAccount;
        $this->statistic = $statistic;
        $this->privateCode = $privateCode;
        $this->referCode = $referCode;
        $this->commission = $commission;
        $this->memberWithdraw = $memberWithdraw;
        $this->scoreGoods = $scoreGoods;
        $this->address = $address;
        $this->goodsStock = $goodsStock;
        $this->silentAuth = $silentAuth;
        $this->memberWaterBillLog = $memberWaterBillLog;
    }

    public function getOrder()
    {
        $hideHeader = false;
        if (request('shop_id')) {
            $shopId = request('shop_id');
            $hideHeader = true;
        } else {
            $shopId = session('shop_info.id');
        }
        $rows = $this->order->getOwnOrderList($shopId);
        if ($rows['data']) {
            foreach ($rows['data'] as &$v) {
                $v['back'] = 0;
                foreach ($v['order_goods'] as $m) {
                    if ($m['goods_category_id'] == $this->order->back_category_id) {
                        $v['back'] = 1;
                    }
                }
            }
        }
        $ext = $this->picture->config['saveExt'];
        $mini = 60;
        if ($this->picture->config['cut_Mini_Size']) {
            $miniArr = explode(',', $this->picture->config['cut_Mini_Size']);
            $mini = $miniArr[0];
        }
        $listType = $this->order->listType;
        if ($hideHeader) {
            return view('admin.single.order', compact('rows', 'ext', 'mini', 'listType', 'hideHeader'));
        }
        return view('admin.single.order', compact('rows', 'ext', 'mini', 'listType'));
    }

    public function getOrderInfo()
    {

    }

    public function getOrderCancle()
    {
//        if (request('type')) {
        $res = $this->order->cancel();
        if (!$res) {
            return $this->error($this->order->getError() ? $this->order->getError() : '未知错误');
        }
        return $this->success($res);
//        }
//        return view('admin.single.order_cancle');
    }

    public function getOrderSend()
    {
        if (request('type')) {
            $orderData = $this->order->send();
            if (!$orderData) {
                return $this->error($this->order->getError() ? $this->order->getError() : '未知错误');
            }
            set_time_limit(0);
            ob_end_clean();
            header("Connection: close");
            header("HTTP/1.1 200 OK");
            header("Content-Type: application/json;charset=utf-8");// 如果前端要的是json则添加，默认是返回的html/text
            ob_start();
            echo json_encode(['status' => 1, 'url' => urlPlat('single', 'getOrder'), 'info' => request('re',0) ? '改派成功' : '派单成功']);// 输出结果到前端
            $size = ob_get_length();
            header("Content-Length: $size");
            ob_end_flush();
            flush();
            if (function_exists("fastcgi_finish_request")) { // yii或yaf默认不会立即输出，加上此句即可（前提是用的fpm）
                fastcgi_finish_request(); // 响应完成, 立即返回到前端,关闭连接
            }
            ignore_user_abort(true);// 在关闭连接后，继续运行php脚本
            set_time_limit(0);
            $shopInfo = $this->shop->_redisGetOneBySid($orderData['shop_id']);
            $resend = request('re', 0);//改派
            if ($resend) {
                if ($shopInfo['send_mode'] == 1) {
                    // 打印订单
                    (new \App\Support\Printer())->typeSetting($orderData);
                } else {
                    $this->wxTpl->newOrderMsg($orderData, $orderData['shop_id'], $resend);
                }
            }
            $this->wxTpl->preSendOrderMsg($orderData);
            exit;
        }
        $worker_id = request('worker_id');
        $rows = $this->worker->_getList(['shop_id' => session('shop_info.id'), 'worker_type' => 0,'status'=>1], 'id,name,code')->toArray();
        return view('admin.single.order_send', compact('rows', 'worker_id'));
    }

    public function getOrderDelete()
    {
        $res = $this->order->deleteOrder();
        if (!$res) {
            return $this->error($this->order->getError() ? $this->order->getError() : '未知错误');
        }
        return $this->success($res);
    }

    public function getMember()
    {
        $rows = $this->member->getMemberList();
        $keyword = trim(request('keyword', ''));
        $type = $keyword ? request('type', 0) : 0;
        $shopInfo = $this->shop->_redisGetOneBySid(session('shop_info.id'));
        return view('admin.single.member', compact('rows', 'keyword', 'type', 'shopInfo'));
    }

    public function getMemberCash()
    {
        $rows = $this->memberCash->getList();
        $status = request('status', 'all');
        $shopId = request('shop_id', 0);
        $type = request('type', 0);
        $keyword = trim(request('keyword', ''));
        $status_text = '全部';
        ($status == 0 && is_numeric($status)) && $status_text = '未退';
        $status == 1 && $status_text = '已退';
        if (!$rows['data']) {
            if (!$shopId && $type == 1 && $keyword) {
                $where['id'] = $keyword;
                $where['shop_id'] = session('shop_info.id');
                $info = $this->member->_getOne($where, 'shop_id');
                if (!$info) {
                    return $this->error('该用户不存在', urlPlat('single','getMemberCash'));
                }
                $shopId = $info['shop_id'];
            }
        }
        return view('admin.single.cash_index', compact('rows', 'type', 'keyword', 'status', 'status_text', 'shopId'));
    }

    public function getMemberCashInfo()
    {
        $info = $this->memberCash->_getOneById(request('id'));
        $shop = $this->shop->_redisGetOneBySid(request('shop_id'));
        $member = $this->member->_getOneById(request('mid'));
        $bucketData = $this->bucketData->_getJionList('category', ['shop_id' => session('shop_info.id')])->toArray();
        $hideHeader = 1;
        return view('admin.member.cash_info', compact('shop', 'member', 'bucketData', 'info', 'hideHeader'));
    }


    public function getMemberInfo()
    {
        $info = $this->goods->_getOneById(request('id'));
        return view('admin.member.info', compact('info'));
    }

    /* 新增押金 */
    public function getMemberAddCash()
    {
        $shop = $this->shop->_redisGetOneBySid(request('shop_id'));
        $member = $this->member->_getOne(['id'=>request('id'),'shop_id'=>session('shop_info.id')]);
        if (!$member) {
            return $this->error('该用户不存在', urlPlat('single','getMemberCash'));
        }
        $bucketData = $this->bucketData->_getJionList('category', ['shop_id' => session('shop_info.id')])->toArray();
        return view('admin.member.cash', compact('shop', 'member', 'bucketData'));
    }


    public function postMemberAddCash()
    {
        $res = $this->memberCash->addOrUpdate(request('shop_id'));
        if (!$res) {
            return $this->error($this->memberCash->getError() ? $this->memberCash->getError() : '未知错误');
        }
        return $this->success('添加押金成功', urlPlat('single','getMemberCash',['keyword'=>request('mid'),'admin_id'=>request('admin_id'),'shop_id'=>request('shop_id'),'type'=>1]));
    }

    /* 老用户导入 */
    public function getMemberImport()
    {
        $shop = $this->shop->_getOne(['id' => request('shop_id')]);
        $shop = $shop ? $shop->toArray() : [];
        $bucketData = $this->bucketData->_getJionList('category', ['shop_id' => request('shop_id')])->toArray();
        if (!$bucketData) {
            return $this->error('请先添加店铺分类');
        }
        $waterBill = $this->waterBill->_getList(['shop_id' => request('shop_id'), 'status' => 1])->toArray();
        if (!$waterBill) {
            return $this->error('请先添加水票');
        }
        $member = $this->member->_getOneById(request('id'));
        return view('admin.member.import', compact('shop', 'bucketData', 'waterBill', 'member'));
    }

    public function postMemberImport()
    {
        $res = $this->member->import(request('shop_id'), request('admin_id'));
        if (!$res) {
            return $this->error($this->member->getError() ? $this->member->getError() : '未知错误');
        }
        return $this->success('导入成功');
    }

    public function getMemberBackCash()
    {
        $info = $this->memberCash->_getOneById(request('id'));
        if (!$info) {
            return $this->error('非法操作');
        }
        if ($info && $info['status']) {
            return $this->error('该押金已退，请刷新当前页面查看最新数据');
        }
        $num = $this->memberCash->_count(['mid' => $info['mid'], 'status' => 0, 'id' => ['<>', $info['id']]], 'id');
        $shop = $this->shop->_redisGetOneBySid(request('shop_id'));
        $member = $this->member->_getOneById(request('mid'));
        $bucketData = $this->bucketData->_getJionList('category', ['shop_id' => request('shop_id')])->toArray();
        return view('admin.member.cash', compact('shop', 'member', 'bucketData', 'info', 'num'));
    }

    public function postMemberBackCash()
    {
        $res = $this->memberCash->addOrUpdate(request('shop_id'));
        if (!$res) {
            return $this->error($this->memberCash->getError() ? $this->memberCash->getError() : '未知错误');
        }
        return $this->success('操作成功', urlPlat('single','getMemberCash',['keyword'=>request('mid'),'admin_id'=>request('admin_id'),'shop_id'=>request('shop_id'),'type'=>1]));
    }

    /* 水票充值 */
    public function getMemberCharge()
    {
        $shop = $this->shop->_getOne(['id' => request('shop_id')]);
        $shop = $shop ? $shop->toArray() : [];
        $waterBill = $this->waterBill->_getList(['shop_id' => request('shop_id'), 'status' => 1])->toArray();
        if (!$waterBill) {
            return $this->error('请先添加水票');
        }
        $member = $this->member->_getOneById(request('id'));
        return view('admin.single.memberl_charge', compact('shop', 'waterBill', 'member'));
    }

    public function postMemberCharge()
    {
        $bill_id = intval(request('bill_id'));
        $bill_num = intval(request('waterbill_num'));
        $mid = intval(request('id'));
        $money = intval(request('money'));
        $res = $this->member->charge($bill_id, $bill_num, $mid, request('shop_id'), $money);
        if (!$res) {
            return $this->error($this->member->getError() ? $this->member->getError() : '未知错误');
        }
        return $this->success('充值成功', 'javascript:history.back(-2);');
    }

    public function anyChangeMemberStatus()
    {
        $ids = is_array(request('ids')) ? request('ids') : [request('ids')];
        $xcx_openid = request('xcx_openid');
        $shop_id = request('shop_id');
        $status = request('status');
        if (empty($ids)) {
            return $this->error('请选择要操作的数据');
        }
        $where['id'] = ['in', $ids];
        switch ($status) {
            case 0  :
                $this->member->_redisGenerateByXcxOpenId($xcx_openid, $shop_id);
                return $this->forbid($this->member, $where, ['success' => '禁用成功', 'error' => '禁用失败']);
            case 1  :
                $this->member->_redisGenerateByXcxOpenId($xcx_openid, $shop_id);
                return $this->resume($this->member, $where, ['success' => '启用成功', 'error' => '启用失败']);
            default :
                return $this->error('参数错误');
        }
    }

    public function getShop()
    {
        $rows = $this->shop->getShopList();
        return view('admin.single.shop', compact('rows'));
    }

    public function getShopInfo()
    {
        if (request('shop_id')) {
            $shopId = request('shop_id');
        } else {
            $shopId = session('shop_info')['id'];
        }
        $info = $this->shop->_getOneById($shopId);
        return view('admin.shop.info', compact('info'));
    }

    public function getShopAdd()
    {
        return view('admin.shop.edit');
    }

    public function postShopAdd()
    {
        $res = $this->shop->addOrUpdate();
        if (!$res) {
            return $this->error($this->shop->getError() ? $this->shop->getError() : '新增失败');
        }
        $shopInfo = $this->shop->_getOneById($res);
        addSession('shop_info', $shopInfo->toArray());
        return $this->success('新增成功', urlAdmin('single', 'getShop'));
    }

    /* 编辑分类 */
    public function getShopEdit()
    {
        $info = $this->shop->_getOneById(request('id'));
        return view('admin.shop.edit', compact('info'));
    }

    public function postShopEdit()
    {
        $res = $this->shop->addOrUpdate();
        if (!$res) {
            return $this->error($this->shop->getError() ? $this->shop->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('single', 'getShop'));
    }

    public function getShopSetting()
    {
        $shop_id = request('id');
        $admin_id = request('admin_id');
        $info = $this->shop->_getOneById(request('id'));
        $ext = $this->picture->config['saveExt'];
        return view('admin.shop.setting', compact('info', 'ext', 'shop_id', 'admin_id'));
    }

    public function postShopSetting()
    {
        $res = $this->shop->setting();
        if (!$res) {
            return $this->error($this->shop->getError() ? $this->shop->getError() : '未知错误');
        }
        return $this->success('设置成功', urlAdmin('single', 'getShop'));
    }

    public function anyChangeShopStatus()
    {
        $id = request('id');
        $status = request('status');
        $shop = $this->shop->_getOneById($id);
        if (!$shop) {
            return $this->error('该打印机不存在');
        }
        $where['id'] = ['=', $id];
        switch ($status) {
            case 0  :
                return $this->forbid($this->shop, $where, ['success' => '禁用成功', 'error' => '禁用失败']);
            case 1  :
                return $this->resume($this->shop, $where, ['success' => '启用成功', 'error' => '启用失败']);
            default :
                return $this->error('参数错误');
        }
    }

    public function getGoods()
    {
        $rows = $this->shopGoods->getOwnGoodsListById(session('shop_info')['id']);
        $ext = $this->picture->config['saveExt'];
        $mini = 60;
        if ($this->picture->config['cut_Mini_Size']) {
            $miniArr = explode(',', $this->picture->config['cut_Mini_Size']);
            $mini = $miniArr[0];
        }
        return view('admin.single.goods', compact('rows', 'ext', 'mini'));
    }

    public function getGoodsAdd()
    {
        $goodsCategory = $this->goodsCategory->getCategoryTree();
        unset($goodsCategory[0]);
        $brand = $this->brand->_getList([], '*', ['sort' => 'asc'])->toArray();
        $bucketCategory = $this->shopBucketCategory->_getOne(['shop_id' => session('shop_info')['id']], 'category_data');
        if (!$bucketCategory) {
            return $this->error('请先添加水桶品牌');
        }
        $bucketCategory = $bucketCategory['category_data'];
        $ext = $this->picture->config['saveExt'];
        return view('admin.goods.edit', compact('goodsCategory', 'bucketCategory', 'brand', 'ext'));
    }

    public function postGoodsAdd()
    {
        $res = $this->goods->addOrUpdate(1);
        if (!$res) {
            return $this->error($this->goods->getError() ? $this->goods->getError() : '未知错误');
        }
        return $this->success('新增成功', urlAdmin('single', 'getGoods'));
    }

    public function getGoodsEdit()
    {
        $goodsCategory = $this->goodsCategory->getCategoryTree();
        unset($goodsCategory[0]);
        $brand = $this->brand->_getList([], '*', ['sort' => 'asc'])->toArray();
        $info = $this->goods->_getOneById(request('id'));
        $info = $info ? $info->toArray() : [];
        $bucketCategory = $this->bucketCategory->_getList(['status' => 1, 'admin_id' => is_login()], '*', ['sort' => 'asc'])->toArray();
        $ext = $this->picture->config['saveExt'];
        return view('admin.goods.edit', compact('goodsCategory', 'bucketCategory', 'brand', 'info', 'ext'));
    }

    public function postGoodsEdit()
    {
        $res = $this->goods->addOrUpdate();
        if (!$res) {
            return $this->error($this->goods->getError() ? $this->goods->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('single', 'getGoods'));
    }

    public function anyChangeGoodsStatus()
    {
        $method = request('method');
        $ids = array_unique((array)request('ids'));
        if (empty($ids)) {
            return $this->error('请选择要操作的数据!');
        }
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        $where['id'] = ['in', $ids];
        $shopId = request('shop_id');
        switch (strtolower($method)) {
            case 'up':
                $res = $this->shopGoods->_update($where, ['status' => 1]);
                if (!$res) {
                    return $this->error('上架失败!');
                }
                $this->shopGoods->_redisGenerateGoodsListBySid($shopId);
                return $this->success('上架成功!');
            case 'down':
                $res = $this->shopGoods->_update($where, ['status' => -1]);
                if (!$res) {
                    return $this->error('下架失败!');
                }
                $this->shopGoods->_redisGenerateGoodsListBySid($shopId);
                return $this->success('下架成功!');
            default:
                return $this->error('参数非法');
        }
    }

    public function getGoodsStock()
    {
        $id = request('id');
        $info = $this->shopGoods->_getOneById($id);
        $ext = $this->picture->config['saveExt'];
        return view('admin.goods.stock', compact('info', 'ext'));
    }

    public function postGoodsStock()
    {
        $id = request('id');
        $num = request('num', 0);
        if (!is_numeric($num) && is_integer($num)) {
            return $this->error('请输入正整数');
        }
        $info = $this->shopGoods->_getOneById($id);
        if (!$info) {
            return $this->error('入库失败');
        }
        $res = $this->goodsStock->addGoodsStock($info, $num);
        if (!$res) {
            $error = $this->goodsStock->getError() ? $this->goodsStock->getError() : '入库失败';
            return $this->error($error);
        }
        return $this->success('入库成功', urlPlat('single', 'getGoods'));
    }

    // 入库明细列表
    public function getStockList()
    {
        $id = request('id');
        $rows = $this->goodsStock->_getPageList(['shop_goods_id' => $id], '*', ['id' => 'desc']);
        $hideHeader = 1;
        return view('admin.goods.stockList', compact('rows', 'hideHeader'));
    }

    /**
     * 排序
     */
    public function getGoodsSort()
    {
        $where['status'] = 1;
        if (request()->has('ids')) {
            $where['id'] = ['in', [request('ids')]];
        }
        $where['shop_id'] = session('shop_info')['id'];
        $rows = $this->shopGoods->_getList($where, 'id,goods_name', ['sort' => 'asc', 'id' => 'asc'])->toArray();
        return view('admin.shop_goods.sort', compact('rows'));
    }

    public function postGoodsSort()
    {
        $ids = request('ids');
        $ids = explode(',', $ids);
        $data = [];
        foreach ($ids as $key => $value) {
            $data[] = ['id' => $value, 'sort' => $key + 1];
        }
        $res = $this->shopGoods->_updateBatch($data);
        if (!$res) {
            return $this->error('排序失败！');
        }
        $this->shopGoods->_redisGenerateGoodsListBySid(session('shop_info')['id']);
        return $this->success('排序成功！');
    }

    public function getBill()
    {
        $rows = $this->shopGoods->getOwnGoodsListWithBill(session('shop_info')['id']);
        $ext = $this->picture->config['saveExt'];
        $mini = 60;
        if ($this->picture->config['cut_Mini_Size']) {
            $miniArr = explode(',', $this->picture->config['cut_Mini_Size']);
            $mini = $miniArr[0];
        }
        return view('admin.single.bill', compact('rows', 'ext', 'mini'));
    }

    public function getBillInfo()
    {
        $info = $this->waterBill->_getOne(['goods_id' => request('id'), 'shop_id' => session('shop_info')['id']]);
        $ext = $this->picture->config['saveExt'];
        $mini = 60;
        if ($this->picture->config['cut_Mini_Size']) {
            $miniArr = explode(',', $this->picture->config['cut_Mini_Size']);
            $mini = $miniArr[0];
        }
        return view('admin.bill.info', compact('info', 'ext', 'mini'));
    }

    public function getBillAdd()
    {
        $billCategory = $this->shopWaterBillCategory->getShopBillCategory(session('shop_info.id'));
        $info = $this->shopGoods->_getOne(['id' => request('id')]);
        $ext = $this->picture->config['saveExt'];
        return view('admin.bill.edit', compact('billCategory', 'info', 'ext'));
    }

    public function postBillAdd()
    {
        $res = $this->waterBill->addOrUpdate();
        if (!$res) {
            return $this->error($this->waterBill->getError() ? $this->waterBill->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('single', 'getBill', ['page' => request('page')]));
    }

    public function getBillEdit()
    {
        $billCategory = $this->shopWaterBillCategory->getShopBillCategory(session('shop_info.id'));
        $info = $this->waterBill->_getOne(['shop_goods_id' => request('id'), 'status' => 1]);
        $info = $info ? $info->toArray() : [];
        $ext = $this->picture->config['saveExt'];
        return view('admin.bill.edit', compact('billCategory', 'info', 'ext'));
    }

    public function postBillEdit()
    {
        $res = $this->waterBill->edit();
        if (!$res) {
            return $this->error($this->waterBill->getError() ? $this->waterBill->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('single', 'getBill'));
    }

    public function anyChangeBillStatus()
    {
        $method = request('method');
        $ids = array_unique((array)request('ids'));
        if (empty($ids)) {
            return $this->error('请选择要操作的数据!');
        }
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        $where['id'] = ['in', $ids];
        $shopId = request('shop_id');
        switch (strtolower($method)) {
            case 'up':
                $res = $this->waterBill->_update($where, ['status' => 1]);
                if (!$res) {
                    return $this->error('上架失败!');
                }
                $this->waterBill->_redisGenerateBillListBySid($shopId);
                return $this->success('上架成功!');
            case 'down':
                $res = $this->waterBill->_update($where, ['status' => -1]);
                if (!$res) {
                    return $this->error('下架失败!');
                }
                $this->waterBill->_redisGenerateBillListBySid($shopId);
                return $this->success('下架成功!');
            default:
                return $this->error('参数非法');
        }
    }

    /**
     * 排序
     */
    public function getBillSort()
    {
        $where['status'] = 1;
        $where['admin_id'] = is_login();
        if (request()->has('ids')) {
            $where['id'] = ['in', [request('ids')]];
        }
        if (request('shop_id')) {
            $where['shop_id'] = intval(request('shop_id'));
        }
        $rows = $this->waterBill->_getList($where, 'id,goods_name', ['sort' => 'asc'])->toArray();
        return view('admin.bill.sort', compact('rows'));
    }

    public function postBillSort()
    {
        $ids = request('ids');
        $ids = explode(',', $ids);
        $data = [];
        foreach ($ids as $key => $value) {
            $data[] = ['id' => $value, 'sort' => $key + 1];
        }
        $res = $this->waterBill->_updateBatch($data);
        if (!$res) {
            return $this->error('排序失败！');
        }
        $this->waterBill->_redisGenerateBillListBySid(request('shop_id'));
        return $this->success('排序成功！');
    }

    public function getBillCategory()
    {
        $tree = $this->waterbillCategory->_getList(['admin_id' => is_login()], '*', ['sort' => 'asc'])->toArray();
        return view('admin.single.bill_category', compact('tree'));
    }

    public function getBillCategoryAdd()
    {
        return view('admin.waterbill_category.edit');
    }

    public function postBillCategoryAdd()
    {
        $res = $this->waterbillCategory->addOrUpdate(1);
        if (!$res) {
            return $this->error($this->waterbillCategory->getError() ? $this->waterbillCategory->getError() : '新增失败');
        }
        return $this->success('新增成功', urlAdmin('single', 'getBillCategory'));
    }

    /* 编辑分类 */
    public function getBillCategoryEdit()
    {
        $info = $this->waterbillCategory->_getOneById(request('id'));
        return view('admin.waterbill_category.edit', compact('info'));
    }

    public function postBillCategoryEdit()
    {
        $res = $this->waterbillCategory->addOrUpdate(1);
        if (!$res) {
            return $this->error($this->waterbillCategory->getError() ? $this->waterbillCategory->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('single', 'getBillCategory'));
    }

    public function anyChangeBillCategoryStatus()
    {
        $status = request('status');
        $ids = array_unique((array)request('ids'));
        if (empty($ids)) {
            return $this->error('请选择要操作的数据!');
        }
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        $where['id'] = ['in', $ids];
        switch ($status) {
            case 0 :
                return $this->forbid($this->waterbillCategory, $where, ['success' => '禁用成功', 'error' => '禁用失败']);
            case 1  :
                return $this->resume($this->waterbillCategory, $where, ['success' => '启用成功', 'error' => '启用失败']);
            default:
                return $this->error('参数非法');
        }
    }

    public function getBucketCategory()
    {
        $tree = $this->bucketCategory->_getList(['admin_id' => is_login()], '*', ['sort' => 'asc'])->toArray();
        return view('admin.single.bucket_category', compact('tree'));
    }

    public function getBucketCategoryAdd()
    {
        $category = $this->bucketCategory->checkParentCategory();
        if (!$category) {
            return $this->error($this->bucketCategory->getError() ? $this->bucketCategory->getError() : '未知错误');
        }
        $info['pid'] = request('pid');
        return view('admin.bucket_category.edit', compact('category', 'info'));
    }

    public function postBucketCategoryAdd()
    {
        $res = $this->bucketCategory->addOrUpdate(1);
        if (!$res) {
            return $this->error($this->bucketCategory->getError() ? $this->bucketCategory->getError() : '新增失败');
        }
        return $this->success('新增成功', urlAdmin('single', 'getBucketCategory'));
    }

    public function getBucketCategoryEdit()
    {
        $category = $this->bucketCategory->checkParentCategory();
        if (!$category) {
            return $this->error($this->bucketCategory->getError() ? $this->bucketCategory->getError() : '未知错误');
        }
        /* 获取分类信息 */
        $info = request('id') ? $this->bucketCategory->getInfo(request('id')) : '';
        return view('admin.bucket_category.edit', compact('info', 'category'));
    }

    public function postBucketCategoryEdit()
    {
        $res = $this->bucketCategory->addOrUpdate(1);
        if (!$res) {
            return $this->error($this->bucketCategory->getError() ? $this->bucketCategory->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('single', 'getBucketCategory'));
    }

    public function anyChangeBucketCategoryStatus()
    {
        $status = request('status');
        $ids = array_unique((array)request('ids'));
        if (empty($ids)) {
            return $this->error('请选择要操作的数据!');
        }
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        $where['id'] = ['in', $ids];
        switch ($status) {
            case 0 :
                return $this->forbid($this->bucketCategory, $where, ['success' => '禁用成功', 'error' => '禁用失败']);
            case 1  :
                return $this->resume($this->bucketCategory, $where, ['success' => '启用成功', 'error' => '启用失败']);
            default:
                return $this->error('参数非法');
        }
    }

    public function getBucketData()
    {
        $rows = $this->bucketData->getOwnShopDataList(session('shop_info')['id']);
        $shop = $this->shop->_getOneById(session('shop_info')['id']);
        $shop = $shop ? $shop->toArray() : [];
        $category = $this->bucketCategory->_getList(['admin_id' => is_login()], '*', ['sort' => 'asc'])->toArray();
        return view('admin.single.bucket_data', compact('rows', 'category', 'shop'));
    }

    public function getBucketDataAdd()
    {
//        $category = $this->bucketCategory->getCache();
        $category = $this->bucketCategory->_getList(['admin_id' => is_login(), 'status' => 1], '*', ['sort' => 'asc'])->toArray();
        $shop = $this->shop->_getOneById(session('shop_info')['id']);
        $shop = $shop ? $shop->toArray() : [];
        return view('admin.bucket.edit', compact('category', 'shop'));
    }

    public function postBucketDataAdd()
    {
        $res = $this->bucketData->addOrUpdate(session('shop_info')['id']);
        if (!$res) {
            return $this->error($this->bucketData->getError() ? $this->bucketData->getError() : '未知错误');
        }
        return $this->success('新增成功', urlAdmin('single', 'getBucketData'));
    }


    /* 编辑分类 */
    public function getBucketDataEdit()
    {
//        $category = $this->bucketCategory->getCache();
        $category = $this->bucketCategory->_getList(['admin_id' => is_login(), 'status' => 1], '*', ['sort' => 'asc'])->toArray();
        $info = $this->bucketData->_getJionOne('shop', ['id' => request('id')])->toArray();
        return view('admin.bucket.edit', compact('category', 'info'));
    }

    public function postBucketDataEdit()
    {
        $res = $this->bucketData->addOrUpdate();
        if (!$res) {
            return $this->error($this->bucketData->getError() ? $this->bucketData->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('single', 'getBucketData'));
    }

    public function getBucketDataLog()
    {
//        $shop = $this->shop->_getOneById(session('shop_info')['id'])->toArray();
        $shop = $this->shop->_redisGetOneBySid(request('shop_id'));
        $rows = $this->backLogData->getLogList(request('shop_id'), request('bucket_category_id'));
        return view('admin.single.log_list', compact('rows', 'shop'));
    }

    public function getWorker()
    {
        $rows = $this->worker->getOwnWorkerList(session('shop_info')['id']);
        return view('admin.single.worker', compact('rows'));
    }

    public function getWorkerInfo()
    {
        $info = $this->worker->_getOneById(request('id'));
        return view('admin.worker.info', compact('info'));
    }

    public function getWorkerAdd()
    {
        return view('admin.worker.edit');
    }

    public function postWorkerAdd()
    {
        $res = $this->worker->addOrUpdate(session('shop_info')['id']);
        if (!$res) {
            return $this->error($this->worker->getError() ? $this->worker->getError() : '未知错误');
        }
        if (request('shop_id')) {
            return $this->success('新增成功', urlAdmin('worker', 'getShopIndex', ['shop_id' => request('shop_id')]));
        }
        return $this->success('新增成功', urlAdmin('single', 'getWorker'));
    }

    public function getWorkerEdit()
    {
        $info = $this->worker->_getOneById(request('id'))->toArray();
        return view('admin.worker.edit', compact('info'));
    }

    public function postWorkerEdit()
    {
        $res = $this->worker->addOrUpdate(session('shop_info')['id']);
        if (!$res) {
            return $this->error($this->worker->getError() ? $this->worker->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('single', 'getWorker'));
    }

    public function getWorkerRemoveBindWx()
    {
        $res = $this->worker->removeBindWx(request('id'));
        if (!$res) {
            return $this->error($this->worker->getError() ? $this->worker->getError() : '未知错误');
        }
        return $this->success($res);
    }

    public function anyChangeWorkerStatus()
    {
        $ids = is_array(request('ids')) ? request('ids') : [request('ids')];
        $status = request('status');
        if (empty($ids)) {
            return $this->error('请选择要操作的数据');
        }
        $where['id'] = ['in', $ids];
        switch ($status) {
            case -1 :
                $this->worker->_redisGenerateByIds($ids);
                return $this->delete($this->worker, $where, ['success' => '禁用成功', 'error' => '禁用失败']);
            case 0  :
                $this->worker->_redisGenerateByIds($ids);
                return $this->forbid($this->worker, $where, ['success' => '禁用成功', 'error' => '禁用失败']);
            case 1  :
                $this->worker->_redisGenerateByIds($ids);
                return $this->resume($this->worker, $where, ['success' => '启用成功', 'error' => '启用失败']);
            default :
                return $this->error('参数错误');
        }
    }

    public function getWechat()
    {
        $ext = (new Picture())->config['saveExt'];
        $aid = 1;
        $info = $this->wechatSet->_getOne(['admin_id' => $aid]);
        $imgCount = 0;
        if ($info) {
            if ($info['wx_app_id']) {
                if (file_exists(public_path() . '/uploads/share/' . $info['wx_app_id'] . '_1' . '.' . $ext)) {
                    $imgCount = 1;
                }
            }
        }

        $qrImg = '';
        if (file_exists(public_path() . '/uploads/qrImg/' . $info['wx_app_id'] . '_qr' . '.' . $ext)) {
            $qrImg = '/uploads/qrImg/' . $info['wx_app_id'] . '_qr' . '.' . $ext;
        }
        $ctr = 'single';
        return view('admin.wechat.set', compact('info', 'imgCount', 'ext', 'qrImg', 'ctr'));
    }

    public function postWechat()
    {
        $res = $this->wechatSet->addOrUpdate();
        if (!$res) {
            return $this->error($this->wechatSet->getError() ? $this->wechatSet->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('single', 'getWechat'));
    }


    public function getCash()
    {
        $shopList = $this->shop->_getList(['admin_id' => is_login()])->toArray();
        $rows = $this->memberCash->getList();
        if (request('shop_id')) {
            foreach ($shopList as $v) {
                if ($v['id'] == request('shop_id')) {
                    $curentShop = $v;
                }
            }
        }
        return view('admin.member.cash', compact('rows', 'shopList', 'curentShop'));
    }

    public function getInfo()
    {
        $info = $this->goods->_getOneById(request('id'));
        return view('admin.member.info', compact('info'));
    }

    /* 新增押金 */
    public function getAddCash()
    {
        $shop = $this->shop->_getOne(['id' => request('shop_id')]);
        $shop = $shop ? $shop->toArray() : [];
        $member = $this->member->_getOneById(request('id'));
        $bucketData = $this->bucketData->_getJionList('category', ['shop_id' => request('shop_id')])->toArray();
        return view('admin.member.cash', compact('shop', 'member', 'bucketData'));
    }


    public function postAddCash()
    {
        $res = $this->memberCash->addOrUpdate(request('shop_id'));
        if (!$res) {
            return $this->error($this->memberCash->getError() ? $this->memberCash->getError() : '未知错误');
        }
        return $this->success('添加押金成功', urlAdmin('single', 'getMember'));
    }

    /* 老用户导入 */
    public function getImport()
    {
        $bucketData = $this->bucketData->_getJionList('category', ['shop_id' => request('shop_id')])->toArray();
        if (!$bucketData) {
            return $this->error('请先添加店铺分类');
        }
        $waterBill = $this->waterBill->_getList(['shop_id' => session('shop_info')['id']]);
        if (!$waterBill) {
            return $this->error('请先添加水票');
        }
        $member = $this->member->_getOneById(request('id'));
        return view('admin.member.import', compact('bucketData', 'waterBill', 'shopList', 'member'));
    }

    public function postImport()
    {
        $res = $this->member->import();
        if (!$res) {
            return $this->error($this->member->getError() ? $this->member->getError() : '未知错误');
        }
        return $this->success('导入成功', urlAdmin('single', 'getMember'));
    }

    /* 老用户导入 */
    public function getBackCash()
    {
        $info = $this->memberCash->_getOne(['mid' => request('id')]);
        $shopList = $this->shop->_getList(['admin_id' => request('admin_id')])->toArray();
        $member = $this->member->_getOneById(request('id'));
        $bucketData = $this->bucketData->_getJionList('category', ['shop_id' => request('shop_id')])->toArray();
        return view('admin.member.cash', compact('shopList', 'member', 'bucketData', 'info'));
    }

    public function postBackCash()
    {
        $res = $this->memberCash->addOrUpdate();
        if (!$res) {
            return $this->error($this->memberCash->getError() ? $this->memberCash->getError() : '未知错误');
        }
        return $this->success('退还押金成功', urlAdmin('single', 'getMember'));
    }


    public function getShopSliders()
    {
        $shop_id = request('id');
        $admin_id = request('admin_id');
        $info = $this->shop->_getOneById(request('id'));
        $ext = $this->picture->config['saveExt'];
        return view('admin.shop.slider', compact('info', 'ext', 'shop_id', 'admin_id'));
    }

    public function postShopSliders()
    {
        $res = $this->shop->saveSliders();
        if (!$res) {
            return $this->error($this->shop->getError() ? $this->shop->getError() : '未知错误');
        }
        return $this->success('保存成功', urlAdmin('single', 'getShop'));
    }

    public function getShopNotice()
    {
        $shop_id = request('id');
        $admin_id = request('admin_id');
        $info = $this->notice->_redisGetOneBySid($shop_id);
        return view('admin.shop.notice', compact('info', 'shop_id', 'admin_id'));
    }

    public function postShopNotice()
    {
        $res = $this->notice->addOrUpdate();
        if (!$res) {
            return $this->error($this->notice->getError() ? $this->notice->getError() : '未知错误');
        }
        return $this->success('设置成功', urlAdmin('single', 'getShop'));
    }

    public function getShopCharge()
    {
        $shopId = request('id');
        if (!$shopId) {
            return $this->error('非法操作');
        }
        $shopInfo = $this->shop->_redisGetOneBySid($shopId);
        $step = request('step', 1);
        if ($step == 1) {
            $accessInfo = $this->authGroupAccess->_getOne(['aid' => $shopInfo['admin_id']]);
            $serviceInfo = $this->service->_getOne(['group_id' => $accessInfo['group_id']]);
            return view('admin.single.charge_step1', compact('shopInfo', 'serviceInfo'));
        }
        if ($step == 2) {
            $accessInfo = $this->authGroupAccess->_getOne(['aid' => $shopInfo['admin_id']]);
            $serviceInfo = $this->service->_getOne(['group_id' => $accessInfo['group_id']]);
            $order = $this->serviceCharge->addOrder($shopInfo, $serviceInfo);
            if (!$order) {
                return $this->error($this->serviceCharge->getError());
            }
            $config = [
                'appid' => 'wx8a991012d1ea27c6',
                'pay_mchid' => '1501931521',
                'pay_apikey' => 'd9d28111f41d51bd0006ac7df562ca45',
                'notify_url' => urlAdmin('shop', 'anyChargeNotify'),
                'body' => '续费订单编号:' . $order['order_sn']
            ];
            $this->wxPay->setConfig($config);
            $payArr['body'] = $config['body'];
            $payArr['order_sn'] = $order['order_sn'];
            $payArr['total_fee'] = $order['order_amount'];
            $result = $this->wxPay->prepay($payArr, 1);
            if (!$result) {
                return $this->error($this->wxPay->getError() ? $this->wxPay->getError() : '未知错误');
            }
            $img = QrCode::size(298)->generate($result);
            return view('admin.single.charge_step2', compact('shopInfo', 'img', 'order'));
        }
        if ($step == 3) {
            return view('admin.single.charge_step3');
        }
    }

    public function getShopCheckOrderStatus()
    {
        $orderId = request('id');
        if (!$orderId) {
            return error('非法操作');
        }
        $res = $this->serviceCharge->_getOneById($orderId);
        if (!$res) {
            return error('订单不存在');
        }
        if ($res['status'] == 20) {
            addSession('show_notice', '');
            return success();
        }
        return error();
    }

    public function getShopChargeRecord()
    {
        $rows = $this->serviceCharge->getRecord();
        return view('admin.shop.charge_record', compact('rows'));
    }

    public function getMemberAdd()
    {
        $waterBill = $this->waterBill->_getList(['shop_id' => session('shop_info')['id'], 'status' => 1])->toArray();
        if (!$waterBill) {
            return $this->error('请先添加水票');
        }
        return view('admin.single.member_edit', compact('waterBill'));
    }

    public function postMemberAdd()
    {
        $shopInfo = session('shop_info');
        $res = $this->member->addOrUpdate($shopInfo['admin_id'], $shopInfo['id']);
        if (!$res) {
            return $this->error($this->member->getError() ? $this->member->getError() : '未知错误');
        }
        return $this->success('新增成功', urlAdmin('single', 'getMember'));
    }

    public function getMemberEdit()
    {
        /*$memberFields = 'id,shop_id';
        $addressFields = 'id,name,mobile,type,shop_id,company_name,area_position,position_address,address,area_info,address,province_id,city_id,area_id,mid';
        $info = $this->member->_getJionOne('address', ['id' => request('id')], $memberFields, $addressFields, ['is_default' => 1]);
        if (!$info) {
            return $this->error('非法操作');
        }
        $info = $info->toArray();*/

        $shopId = request('shop_id', 0);
        $mid = request('id', 0);
        $memberInfo = $this->member->_getOneById($mid);
        if (!$memberInfo) {
            return $this->error('非法操作');
        }
        $info = ['id' => request('id', 0), 'shop_id' => $shopId];
        $address = $this->address->_getOne(['id' => request('address_id'), 'shop_id' => $shopId]);
        $info['address'] = $address ? $address->toArray() : [];
        $waterBill = $this->waterBill->_getList(['shop_id' => session('shop_info')['id'], 'status' => 1])->toArray();

        return view('admin.single.member_edit', compact('info', 'waterBill'));
    }

    public function postMemberEdit()
    {
        $shopInfo = session('shop_info');
        $res = $this->member->addOrUpdate($shopInfo['admin_id'], $shopInfo['id']);
        if (!$res) {
            return $this->error($this->member->getError() ? $this->member->getError() : '未知错误');
        }
        return $this->success('编辑成功', 'javascript:history.back(-2);');
    }

    public function getAddOrder()
    {
        $shopId = request('shop_id');
        $shop = session('shop_info');
        if (!(request('id') && $shopId)) {
            return $this->error('非法操作');
        }
        $member = $this->member->_getJionOne('defaultAddress', ['id' => request('id')], 'id,name,shop_id,admin_id,worker_id', 'mid,mobile,area_info,address', ['is_default' => 1]);
        $goodsList = $this->shopGoods->_getList(['shop_id' => $shopId, 'status' => 1], 'id,goods_name')->toArray();
        $billList = $this->memberWaterBill->_redisGetBillListByMid(request('id'));
        if ($goodsList && $billList) {
            foreach ($goodsList as $k => $v) {
                foreach ($billList as $m => $n) {
                    if ($n && ($v['id'] == $n['shop_goods_id'])) {
                        $goodsList[$k]['bill'] = $n;
                    }
                }
            }
        }
        return view('admin.member.add_order', compact('shop', 'member', 'goodsList'));
    }

    public function postAddOrder()
    {
        $goodsId = request('goods_id');
        $mid = request('mid');
        $shopId = request('shop_id');
        $adminId = request('admin_id');
        $goodsNum = request('goods_num');
        $money = request('money');
        $orderData = $this->order->creatOrder($mid, $shopId, $adminId, $goodsId, $goodsNum, $money);
        if (!$orderData) {
            return $this->error($this->order->getError() ? $this->order->getError() : '未知错误');
        }
        $this->wxTpl->newOrderMsg($orderData, $shopId);
        (new \App\Support\Printer())->typeSetting($orderData);
        return $this->success('下单成功', urlAdmin('single', 'getOrder'));
    }

    public function getMemberMove()
    {
        $shopId = request('shop_id');
        $shop = $this->shop->_redisGetOneBySid($shopId);
        if (!(request('id') && $shopId)) {
            return $this->error('非法操作');
        }
        $member = $this->member->_getOneById(request('id'), 'id,name,shop_id,admin_id,mobile,area_info,address,company_name');
        return view('admin.member.move', compact('shop', 'member'));
    }

    public function postMemberMove()
    {
        $res = $this->member->yijiao(request('mid'), request('move_id'), request('admin_id'), request('shop_id'));
        if (!$res) {
            return $this->error($this->member->getError() ? $this->member->getError() : '未知错误');
        }
        return $this->success('移交成功', urlPlat('single', 'getMember'), true);
    }

    public function getBillOrder()
    {
        $hideHeader = false;
        if (request('shop_id')) {
            $shopId = request('shop_id');
            $hideHeader = true;
        } else {
            $shopId = session('shop_info.id');
        }
        $rows = $this->waterBillOrder->getOwnOrderList($shopId);
        $ext = $this->picture->config['saveExt'];
        $mini = 60;
        if ($this->picture->config['cut_Mini_Size']) {
            $miniArr = explode(',', $this->picture->config['cut_Mini_Size']);
            $mini = $miniArr[0];
        }
        $listType = $this->waterBillOrder->listType;
        if ($hideHeader) {
            return view('admin.single.bill_order', compact('rows', 'ext', 'mini', 'listType', 'hideHeader'));
        }
        return view('admin.single.bill_order', compact('rows', 'ext', 'mini', 'listType'));
    }

    public function getPeripheralIndex()
    {
        $rows = $this->printer->getPrinterList();
        $ctr = 'single';

        return view('admin.peripheral.printer', compact('rows', 'ctr'));
    }

    public function getPrinterEdit()
    {
        if (request('id')) {
            $info = $this->printer->_getOneById(request('id'));
            if (!$info) {
                return $this->error('非法操作');
            }
            $info = $info->toArray();
            return view('admin.peripheral.printer_add', compact('info'));
        } else {
            return view('admin.peripheral.printer_add');
        }

    }

    public function postPrinterEdit()
    {
        $shop_id = 0;
        if (session('shop_info')) {
            $shopInfo = session('shop_info');
            $admin_id = $shopInfo['admin_id'];
            $shop_id = $shopInfo['id'];
        } else {
            $admin_id = session('admin');
            is_login();
        }

        $res = $this->printer->addOrUpdate($admin_id, $shop_id);
        if (!$res) {
            return $this->error($this->printer->getError() ? $this->printer->getError() : '未知错误');
        }
        return $this->success('新增成功', urlAdmin('single', 'getPeripheralIndex'));
    }

    public function getPrinterAdd()
    {
        $printerInfo = $this->printer->_getOneById(request('id'));
        if (!$printerInfo) {
            return $this->error($this->printer->getError() ?: '未知错误');
        }
        $printerSupport = new \App\Support\Printer();
        $str = $printerInfo['serial_number'] . '#' . $printerInfo['auth_code'];
        $printerSupport->addPrinter($str);
        return $this->success('打印机信息上传成功', urlAdmin('single', 'getPeripheralIndex'));
    }

    public function anyChangePrinterStatus()
    {
        $id = request('id');
        $status = request('status');
        $printer = $this->printer->_getOneById($id);
        if (!$printer) {
            return $this->error('该打印机不存在');
        }
        $where['id'] = ['=', $id];
        switch ($status) {
            case 0  :
                return $this->forbid($this->printer, $where, ['success' => '禁用成功', 'error' => '禁用失败']);
            case 1  :
                return $this->resume($this->printer, $where, ['success' => '启用成功', 'error' => '启用失败']);
            default :
                return $this->error('参数错误');
        }
    }

    public function getPrinterDel()
    {
        $id = request('id');
        $printer = $this->printer->_getOneById($id);
        if (!$printer) {
            return $this->error('该打印机不存在');
        }
        $where['id'] = ['=', $id];
        $res = $this->printer->_del($where);
        if (!$res) {
            return $this->error('删除失败');
        }
        return $this->success('删除成功');
    }

    public function getAccount()
    {
        $sid = request('shop_id');
        $aid = request('admin_id');
        $shop = $this->shop->_getOneById($sid);
        if (!$shop) {
            return error('店铺不存在');
        }
        if ($shop['admin_id'] != $aid && !is_administrator()) {
            return error('非法操作');
        }

        $info = $this->shop->_getOneById($sid);
        return view('admin.single.account', compact('info'));
    }

    public function postAccount()
    {
        $res = $this->shop->saveAccount();
        if (!$res) {
            return $this->error($this->shop->getError() ? $this->shop->getError() : '未知错误');
        }
        return $this->success('更新成功', urlAdmin('single', 'getShop'));
    }

    public function getQrCode()
    {
        $ext = (new Picture())->config['saveExt'];
        $aid = 1;
        $info = $this->wechatSet->_getOne(['admin_id' => $aid]);

        // 调整二维码生成
        if ($info && $info['wx_app_id'] && $info['wx_app_secret']) {
            $silentAuth = new WechatSilentAuth();
            $result = $silentAuth->createQrCode($info['wx_app_id'], $info['wx_app_secret'], $aid, 1, $ext);
            if (!$result['status']) {
                return $this->error($result['msg']);
            } else {
                return $this->success('生成二维码成功', url($result['data']));
            }
        } else {
            return $this->error('请先完成公众号配置');
        }
    }

    public function getQrDown()
    {
        $fileName = $this->wechatSet->qrDownHandle(1);
        if (!$fileName) {
            return $this->error('微店二维码不存在');
        }

        return response()->download($fileName, time() . '_qr.jpg');
    }

    public function getSimpleQr()
    {
        $serverName = str_replace('/' . request()->path(), '', url()->current());
        $url = $serverName . '/client/simple.html?admin_id=' . plat_admin_id() . '&_=' . time();
        $fileName = public_path() . '/uploads/qrImg/simple_qr_' . plat_admin_id() . '.png';
        if (!file_exists($fileName)) {
            QrCode::format('png')->size(256)->generate($url, $fileName);
        }
        return response()->download($fileName, 'simple_qr.jpg');
    }


    public function getOrderComplete()
    {
        if (!(request('shop_id') && request('id'))) {
            return $this->error('非法操作');
        }
        $res = $this->worker->_redisGetWorkerList(request('shop_id'));
        $workerInfo = [];
        if ($res) {
            foreach ($res as $v) {
                $workerInfo[] = $this->worker->_redisGetOneByWid($v['id']);
            }
        }
        $where['id'] = request('id');
        $where['shop_id'] = request('shop_id');
        $info = $this->order->_getOne($where, 'id,worker_id,type,buyer_id,admin_id,shop_id,order_amount');
        if (!$info) {
            return $this->error('非法操作');
        }
        $info = $info->toArray();
        $where = [];
        $where['admin_id'] = is_login();
        $where['shop_id'] = request('shop_id');
        $bucketData = $this->bucketData->_getJionList('category', $where, 'id,bucket_category_id,shop_id', [], 0, 'id,title')->toArray();
        if (!$bucketData) {
            return $this->error('该店铺没有添加水桶品牌');
        }
        $arr = $bucketData[0];
        $arr['id'] = 0;
        $arr['bucket_category_id'] = '';
        unset($arr['category']);
        $arr['title'] = '请选择水桶品牌';
        foreach ($bucketData as &$v) {
            $v['title'] = $v['category']['title'];
            unset($v['category']);
        }
        array_unshift($bucketData, $arr);
        $back = request('back', 0);
        $where = [];
        $where['mid'] = $info['buyer_id'];
        $where['pay_status'] = 10;
        $where['type'] = 1;
        $recive_bill_money = $this->waterBillOrder->_sum($where, 'order_amount');
        return view('admin.single.order_complete', compact('info', 'workerInfo', 'bucketData', 'back', 'recive_bill_money'));
    }

    public function postOrderComplete()
    {
        $wid = request('worker_id');
        $sid = request('sid');
        $aid = request('aid');
        $oldwid = request('oldwid');
        if (!($wid && $sid && $aid)) {
            return error('非法操作');
        }
        if ($wid != $oldwid) {
            $this->order->_update(['id' => request('id')], ['worker_id' => $wid]);
        }
        $res = $this->order->complete();
        if (!$res) {
            return error($this->order->getError() ? $this->order->getError() : '未知错误');
        }
        return success('操作成功');
    }

    // 数据统计
    public function getStatistic()
    {
        $type = request('type', 'money');
        if (is_administrator()) {
            $where = [];
        } else {
            if (session('shop_info')) {
                $where['id'] = session('shop_info.id');
            } else {
                $where['admin_id'] = plat_admin_id();
            }
        }
        $shops = $this->shop->_getList($where, 'id,shop_name')->toArray();

        switch ($type) {
            case 'delivery':
                // 配送统计
                $shopGoods = $this->statistic->goodsDeliveryStatistic();//商品统计
                $payType = $this->statistic->payTypeDeliveryStatistic();// 支付方式统计
                $worker = $this->statistic->workerDeliveryStatistic();// 送水工统计
                $subView = 'admin.statistic.delivery';
                $data = compact('type', 'shops', 'subView', 'shopGoods', 'payType', 'worker');
                break;
            case 'bill':
                // 水票统计
                $bill = $this->statistic->waterBillStatistic();
                $subView = 'admin.statistic.bill';
                $data = compact('type', 'shops', 'subView', 'bill');
                break;
            case 'bucket':
                // 水桶统计
                $bucket = $this->statistic->bucketDeliveryStatistic();
                $subView = 'admin.statistic.bucket';
                $data = compact('type', 'shops', 'subView', 'bucket');
                break;
            case 'deposit':
                // 押金统计
                $deposit = $this->statistic->depositStatistic();
                $subView = 'admin.statistic.deposit';
                $data = compact('type', 'shops', 'subView', 'deposit');
                break;
            default:
                // 营收统计
                $revenue = $this->statistic->revenueStatistic(); //水票/非水票 统计
                $money = $this->statistic->moneyStatistic(); //款项支付方式/分类 统计
                $goods = $this->statistic->goodsStatistic(); //水票款/订单款 细分商品 统计
                if (!$revenue || !$money || !$goods) {
                    return $this->error($this->statistic->getError());
                }
                $subView = 'admin.statistic.money'; // 视图文件
                $data = compact('type', 'shops', 'subView', 'revenue', 'money', 'goods');
                break;
        }
        $data['ctr'] = 'single';
        $data['action'] = 'getStatistic';
        return view('admin.statistic.index', $data);
    }

    public function getWxpayApply()
    {
        return view('admin.single.wxpay_apply');
    }

    // 专属码列表
    public function getPrivate()
    {
        $keyword = trim(request('keyword', ''));
        $codeStatus = request('code_status', 0);
        $where = [];
        if (!is_administrator()) {
            $where['admin_id'] = plat_admin_id();
        }
        // 查询code关键词
        if ($keyword) {
            $where['code'] = ['like', "%$keyword%"];
        }
        if ($codeStatus) {
            $where['code_status'] = $codeStatus;
        }
        $rows = $this->privateCode->getPrivateCodeList($where);
        $codeStatus = request('codeStatus', 0);
        return view('admin.single.private', compact('rows', 'codeStatus'));
    }

    // 生成专属码
    public function postPrivate()
    {
        $res = $this->privateCode->multiCreateCode();
        if (!$res) {
            return error($this->privateCode->getError() ? $this->privateCode->getError() : '未知错误');
        }
        return success('操作成功');
    }

    // 导出专属码
    public function getExportPrivate()
    {
        $aid = plat_admin_id() == 1 ? 2 : plat_admin_id();
        $limit = request('limit');
        if(!$limit) {
            return $this->error('请输入初始序号及结束序号');
        }
        $limitArr = explode('-', $limit);
        if(count($limitArr) != 2) {
            return $this->error('请按文字提示的格式输入');
        }
        $start = $limitArr[0];
        $end = $limitArr[1];
        if((!is_numeric($start) || is_float($start) || $start < 1) || !is_numeric($end) || is_float($end) || $end < 1) {
            return $this->error('初始序号或结束序号应为正整数');
        }
        if($end - $start < 0) {
            return $this->error('初始序号不能大于结束序号');
        }
        if($end - $start > 4999) {
            return $this->error('一次最多只能导出5000条数据');
        }

        $where['status'] = 1;
        $where['id'] = ['between',$limitArr];
        $rows = $this->privateCode->_getList($where, 'id,code'); //导出未使用的数据
        $data = $rows->map(function ($item) use ($aid) {
            $item = [
                $item['id'],//序列号
                $item['code'],//专属码
                urlHome('Index', 'getEntrance', ['aid' => $aid, 'private_code' => $item['code']], 2)//专属码链接，用于生成二维码
            ];
            return $item;
        })->toArray();
        array_unshift($data, ['序列号', '订水码', '订水二维码链接']);

        return $this->privateCode->exportPrivateExcel($data);
    }

    // 禁用/启用订水码
    public function anyChangePrivateStatus()
    {
        $ids = is_array(request('ids')) ? request('ids') : [request('ids')];
        $shop_id = request('shop_id');
        $status = request('status');
        if (empty($ids)) {
            return $this->error('请选择要操作的数据');
        }
        $where['id'] = ['in', $ids];
        $where['shop_id'] = $shop_id;
        $where['code_status'] = ['=', 3]; // 已绑定用户的订水码才可取消
        $count = $this->privateCode->_count($where, 'id');
        if (!$count) {
            return $this->error('非法操作');
        }
        unset($where['code_status']);
        switch ($status) {
            case 0  :
                return $this->forbid($this->privateCode, $where, ['success' => '禁用成功', 'error' => '禁用失败']);
            default :
                return $this->error('参数错误');
        }
    }

    // 绑定店铺页面
    public function getBindShop()
    {
        if (is_administrator()) {
            $where = [];
        } else {
            $aid = in_array(plat_admin_id(), [1, 2]) ? 2 : plat_admin_id();
            $where['admin_id'] = $aid;
        }
        $shops = $this->shop->_getList($where)->toArray();
        return view('admin.single.bind_code', compact('shops'));
    }

    // 专属码绑定店铺
    public function postBindShop()
    {
        $res = $this->privateCode->bindShopCode();
        if (!$res) {
            return error($this->privateCode->getError() ? $this->privateCode->getError() : '未知错误');
        }
        return success('操作成功');
    }

    // 人人分销
    public function getPersonRefer()
    {
        $referType = 1;
        $rows = $this->member->getMemberReferList($referType);
        $ctr = 'single';
        $method = 'getPersonRefer';
        $title = '人人分销';
        $keyword = trim(request('keyword', ''));
        $type = $keyword ? request('type', 0) : 0;
        return view('admin.refer.member_refer', compact('rows', 'ctr', 'method', 'title', 'type', 'keyword'));
    }

    public function getChannelRefer()
    {
        $referType = 2;
        $rows = $this->member->getMemberReferList($referType);
        $ctr = 'single';
        $method = 'getChannelRefer';
        $title = '渠道分销';
        $keyword = request('keyword', '');
        $type = $keyword ? request('type', 0) : 0;
        return view('admin.refer.member_refer', compact('rows', 'ctr', 'method', 'title', 'type', 'keyword'));
    }

    // 渠道设置
    public function getReferMemberSet()
    {
        $keyword = request('keyword', '');
        $type = $keyword ? request('type', 0) : 0;
        $rows = $this->member->getMemberReferList(1);
        $hideHeader = 1;
        $shops = $this->shop->_getList();
        $ctr = 'single';
        return view('admin.refer.refer_set', compact('rows', 'ctr', 'keyword', 'type', 'shops', 'hideHeader'));
    }

    public function postReferMemberSet()
    {
        $res = $this->referCode->createCodeByMid();
        if (!$res) {
            $error = $this->referCode->getError();
            return error($error ? $error : '未知错误');
        }
        return success('设置成功');
    }

    // 佣金比例设置
    public function getReferRatio()
    {
        $mid = request('mid');
        $info = $this->member->_getOneById($mid);
        $shop = $this->shop->_redisGetOneBySid($info['shop_id']);
        $refer = $this->referCode->_getOne(['mid' => $mid]);
        $title = '佣金设置';
        return view('admin.refer.refer_bind_user', compact('info', 'refer', 'shop', 'title'));
    }

    public function postReferRatio()
    {
        $mid = request('mid');
        $ratio = request('refer_ratio', 0);
        $where['id'] = $mid;
        $where['shop_id'] = $this->sid;
        $memberInfo = $this->member->_getOne($where);
        if (!$memberInfo) {
            return $this->error('该用户不存在');
        }
        if ($memberInfo['refer_id'] > 0 && $ratio == 0) {
            return $this->error('请输入提成比例');
        }
        $res = $this->member->_update(['id' => $mid], ['refer_ratio' => $ratio]);
        if (!$res) {
            return $this->error('编辑失败');
        }
        return $this->success('编辑成功', 'javascript:history.back(-2);');

    }

    // 获取推广二维码
    public function getReferQr()
    {
        $mid = request('mid');
        $memberInfo = $this->member->_getOneById($mid); // 获取推广员信息
        if (!$memberInfo) {
            return $this->error('该用户不存在');
        }
        $referInfo = $this->referCode->_getOneById($memberInfo['refer_id']);
        $data = [
            'aid' => $memberInfo['admin_id'],
            'sid' => $memberInfo['shop_id'],
            'mid' => $mid
        ];
        $size = 220;
        $format = 'png';
        $url = urlHome('Index', 'getEntrance', $data, 2);
        $alias = $memberInfo['id'] . '_' . $memberInfo['nickname'] . '_' . $referInfo['code'];
        $imgResource = 'data:image/png;base64,' . base64_encode(QrCode::format($format)->margin(3)->size($size)->generate($url));
        $baseImg = public_path() . '/admin/images/refer_default.png';
        $code = $referInfo['code'];
        return $this->referCode->handleReferQr($imgResource, $baseImg, $code, $alias, $format);
    }

    // 用户提成列表
    public function getCommission()
    {
        $keyword = request('keyword', '');
        $where = [];
        if (!is_administrator()) {
            $where['member_commission.admin_id'] = plat_admin_id();
        }
        if ($keyword) {
            $where['member.nickname'] = $keyword;
        }

        $rows = $this->commission->getCommissionList($where);
        $ctr = 'single';
        return view('admin.refer.commission', compact('rows', 'ctr'));
    }

    // 提现审批列表
    public function getWithdraw()
    {
        $keyword = request('keyword', '');
        $status = request('status', 0);
        $where = [];
        if(!is_administrator()) {
            if(session('shop_info')) {
                $where['member_withdraw.shop_id'] = session('shop_info.id');
            } else {
                $where['member_withdraw.admin_id'] = plat_admin_id();
            }
        }
        if ($status) {
            $where['member_withdraw.status'] = $status;
        }
        if ($keyword) {
            $where['member.nickname'] = $keyword;
        }

        $rows = $this->memberWithdraw->getWithdrawList($where);

        $ctr = 'single';
        return view('admin.refer.withdraw', compact('rows', 'ctr', 'status'));
    }

    // 提现审核
    public function postAudit()
    {
        $id = request('id');
        $status = request('status');
        $logInfo = $this->memberWithdraw->_getOneById($id);
        if ($logInfo['status'] == $status) {
            return error("编辑失败");
        }
        if ($status == 4) {
            if (!request('reason')) {
                return error('请输入驳回原因');
            }
        }
        $data = [
            'status' => $status
        ];
        if (request('reason')) {
            $data['reason'] = request('reason');
        }

        $res = $this->memberWithdraw->_update(['id' => $id], $data);
        if (!$res) {
            return error('编辑失败');
        } else {
            return success('编辑成功');
        }
    }

    public function getScoreGoods()
    {
        $where = [];
        if (!is_administrator()) {
            $where['admin_id'] = plat_admin_id();
        }
        if (session('shop_info')) {
            $where['shop_id'] = session('shop_info.id');
        }
        if (request('shop_id')) {
            $where['shop_id'] = request('shop_id');
        }
        $rows = $this->scoreGoods->getScoreGoodsList($where);
        $ext = $this->picture->config['saveExt'];
        $mini = 60;
        if ($this->picture->config['cut_Mini_Size']) {
            $miniArr = explode(',', $this->picture->config['cut_Mini_Size']);
            $mini = $miniArr[0];
        }
        $shopWhere = [];
        if (isset($where['admin_id'])) {
            $shopWhere['admin_id'] = $where['admin_id'];
        }
        $shops = $this->shop->_getList($shopWhere);
        $ctr = 'single';
        return view('admin.score_goods.goods', compact('rows', 'ext', 'mini', 'shops', 'ctr'));
    }

    public function getScoreGoodsAdd()
    {
        $goodsCategory = $this->goodsCategory->getCategoryTree();
        unset($goodsCategory[0]);
        $brand = $this->brand->_getList([], '*', ['sort' => 'asc'])->toArray();

        $where['status'] = 1;
        $bucketCategory = $this->shopBucketCategory->getBucketCategoryTree($this->sid, $where);
        if (!$bucketCategory) {
            return $this->error('请先添加水桶品牌');
        }
        $ext = $this->picture->config['saveExt'];
        $shopId = $this->sid;
        return view('admin.score_goods.edit', compact('goodsCategory', 'bucketCategory', 'brand', 'ext', 'shopId'));
    }

    public function postScoreGoodsAdd()
    {
        $res = $this->scoreGoods->addOrUpdate();
        if (!$res) {
            return $this->error($this->goods->getError() ? $this->goods->getError() : '未知错误');
        }
        return $this->success('新增成功', urlPlat('single', 'getScoreGoods'));
    }

    public function getScoreGoodsSort()
    {
        $where['status'] = 1;
        if (request()->has('ids')) {
            $where['id'] = ['in', [request('ids')]];
        }
        $where['shop_id'] = $this->sid;
        $rows = $this->scoreGoods->_getList($where, 'id,goods_name', ['sort' => 'asc', 'id' => 'asc'])->toArray();
        return view('admin.single.sort', compact('rows'));
    }

    public function postScoreGoodsSort()
    {
        $ids = request('ids');
        $ids = explode(',', $ids);
        $data = [];
        foreach ($ids as $key => $value) {
            $data[] = ['id' => $value, 'sort' => $key + 1];
        }
        $res = $this->scoreGoods->_updateBatch($data);
        if (!$res) {
            return $this->error('排序失败！');
        }
        $this->scoreGoods->_redisGetScoreGoodsListKeysBySid($this->sid);
        return $this->success('排序成功！');
    }

    public function anyChangeScoreGoodsStatus()
    {
        $method = request('method');
        $ids = array_unique((array)request('ids'));
        if (empty($ids)) {
            return $this->error('请选择要操作的数据!');
        }
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        $where['id'] = ['in', $ids];
        $shopId = request('shop_id');
        switch (strtolower($method)) {
            case 'up':
                $res = $this->scoreGoods->_update($where, ['status' => 1]);
                if (!$res) {
                    return $this->error('上架失败!');
                }
                $this->scoreGoods->_redisGetScoreGoodsListKeysBySid($shopId);
                return $this->success('上架成功!');
            case 'down':
                $res = $this->scoreGoods->_update($where, ['status' => -1]);
                if (!$res) {
                    return $this->error('下架失败!');
                }
                $this->scoreGoods->_redisGetScoreGoodsListKeysBySid($shopId);
                return $this->success('下架成功!');
            default:
                return $this->error('参数非法');
        }
    }

    public function getScoreGoodsEdit()
    {
        $goodsCategory = $this->goodsCategory->getCategoryTree();
        unset($goodsCategory[0]);
        $brand = $this->brand->_getList([], '*', ['sort' => 'asc'])->toArray();
        $info = $this->scoreGoods->_getOneById(request('id'))->toArray();
        $bucketCategory = $this->bucketCategory->_getList(['status' => 1, 'admin_id' => $this->aid], '*', ['sort' => 'asc'])->toArray();
        $ext = $this->picture->config['saveExt'];
        $shopId = $this->sid;
        return view('admin.score_goods.edit', compact('goodsCategory', 'bucketCategory', 'brand', 'info', 'ext', 'shopId'));
    }

    public function postScoreGoodsEdit()
    {
        $res = $this->scoreGoods->addOrUpdate();
        if (!$res) {
            return $this->error($this->scoreGoods->getError() ? $this->scoreGoods->getError() : '未知错误');
        }
        return $this->success('更新成功', urlPlat('single', 'getScoreGoods'));
    }

    public function getBindWorker()
    {
        if (request('type', 0)) {
            $res = $this->member->changeMemberWorkerId(request('id'), request('worker_id'));
            if (!$res) {
                return $this->error('操作失败');
            }
            return $this->success('绑定成功');
        }
        $workers = $this->worker->_getList(['shop_id' => request('shop_id'), 'status' => 1, 'worker_type' => 0], 'id,name,code')->toArray();
        return view('admin.member.bind_worker', compact('workers'));
    }

    public function getSyncQrCode()
    {
        $data = [
            'action' => 'bindWx',//用于标识推广码操作
            'shopId' => request('shop_id'),
            'mid' => request('id'), //推广员ID
        ];
        $key = 'bind_wx_' . $data['mid'];
        $settings = $this->wechatSet->_getOne(['admin_id' => 1]);
        $syncCode = $this->silentAuth->getTempQrCode($settings['wx_app_id'], $settings['wx_app_secret'], $key, json_encode($data));

        $name = request('name');
        $mobile = request('mobile');
        $address = request('address');
        return view('admin.member.bind_wx', compact('syncCode', 'name', 'mobile', 'address'));
    }

    public function getBucketRecord()
    {
        $rows = $this->bucketLog->_getPageList(['buyer_id' => request('id')], 'buyer_id,buyer_name,bucket_num,send_num,description,created_at', ['id' => 'desc'], 15, 10);
        return view('admin.single.bucket_record', compact('rows'));
    }

    public function getBillRecord()
    {
        $rows = $this->memberWaterBillLog->_getPageList(['mid' => request('id')], '*', ['id' => 'desc'], 15, 10);
        return view('admin.single.bill_record', compact('rows'));
    }
}
